<?php

namespace App\Http\Controllers\Admin\Ad;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Ad\Category;
use App\Http\Requests\Ad\StoreCategory;
use App\Http\Requests\Ad\UpdateCategory;


class CategoryController extends Controller
{
    function __construct()
    {
        view()->share([
           '_cate'=>'am-active',
            '_ads'=>'am-in'
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::orderBy('sort_order')->paginate(4);
        return view('admin.ad.category.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.ad.category.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreCategory $request)
    {
        Category::create($request->all());
        return redirect(route('ad.category.index'))->with('success', '新增成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $category = Category::find($id);
        return view('admin.ad.category.edit', compact('category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateCategory $request, $id)
    {
        $category = Category::find($id);
        $category->update($request->all());
        return redirect(route('ad.category.index'))->with('success', '编辑成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Category::destroy($id);
    }

    /***
     * 多条删除
     */
    public function delete_all(Request $request)
    {

        Category::destroy($request->checked_id);
    }
    /***
     * 改变属性
     */
    public function change_attr(Request $request){
        $category = Category::find($request->id);
        $attr = $request->attr;
        $category->$attr = !$category->$attr;
        $category->save();
    }
    /***
     * 排序
     */
    public function sort_order(Request $request){
        $category = Category::find($request->id);
        $category->sort_order = $request->sort_order;
        $category->save();
    }
}
